package org.mil.bean.dom;

import java.lang.reflect.Field;
import java.util.Arrays;
/**
 * 通用文档对象
 * @author HZK
 *
 */
public class GenericDocumentObject {
	private String[] fieldNames, fieldValues;	//字段名，字段值数组

	public GenericDocumentObject() {
		initFieldNames();
	}

	private void initFieldNames() {
		Field[] fields = this.getClass().getDeclaredFields();
		fieldNames = new String[fields.length];
		for (int i = 0; i < fields.length; i++)
			fieldNames[i] = fields[i].getName();

	}

	private void initFieldValues() {
		Field[] fields = this.getClass().getDeclaredFields();
		fieldValues = new String[fields.length];
		for (int i = 0; i < fields.length; i++)
			try {
				fields[i].setAccessible(true);
				fieldValues[i] = (String) fields[i].get(this);
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}

	}

	public String[] getFieldNames() {
		if (fieldNames == null)
			initFieldNames();
		return fieldNames;
	}

	public String[] getFieldValues() {
		if (fieldValues == null)
			initFieldValues();
		return fieldValues;
	}
	
	
	/**
	 * 通用setter
	 * @param field 字段名
	 * @param value 字段值（字符串形式）
	 */
	public void set(String field, String value) {

		Field f = null;

		try {
			f = this.getClass().getDeclaredField(field);
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (NoSuchFieldException e) {
			e.printStackTrace();
		}

		try {
			f.setAccessible(true);// 设置允许访问
			f.set(this, value);
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}

	}
	/**
	 * 通用getter
	 * @param field 字段名
//	 * @return 字段值（字符串形式）
	 */
	public String get(String field) {
		try {
			Field _field = this.getClass().getDeclaredField(field);
			_field.setAccessible(true);
			return (String) _field.get(this);
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (NoSuchFieldException e) {
			e.printStackTrace();
		}

		return null;

	}

	public static void main(String[] arg) {
		GeneralTrackDO t = new GeneralTrackDO();
		t.set("format", "sss");
		//System.out.println(t.getFormat());
		System.out.println(t.get("format"));
		System.out.println(Arrays.toString(t.getFieldNames()));
		System.out.println(Arrays.toString(t.getFieldValues()));

	}
}
